package com.mall.b2c.controller;

import static com.mall.b2c.Constants.HISTORY_GOODSIDS_COOKIE_NAME;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mall.b2c.bean.GoodsBean;
import com.mall.b2c.bean.Pager;
import com.mall.b2c.hessian.CommentHessian;
import com.mall.b2c.hessian.GoodsExtendHessian;
import com.mall.b2c.hessian.GoodsHessian;
import com.mall.b2c.hessian.MemberExtendHessian;
import com.mall.common.util.CookieUtils;

@Controller
public class GoodsController extends BaseController {
	@Resource private GoodsHessian goodsHessian;
	@Resource private CommentHessian commentHessian;
	@Resource private MemberExtendHessian memberExtendHessian;
	@Resource private GoodsExtendHessian goodsExtendHessian;

	/**
	 * 商品详情页
	 * @param goodsId
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/goods/{goodsId:\\d+}", method=RequestMethod.GET)
	@SuppressWarnings("unchecked")
	public String detail(@PathVariable Long goodsId, Model model){
		String result = goodsHessian.getGoodsDetail(goodsId, null, getMemberId());
		model.addAllAttributes(jsonToObj(result, Map.class));
		return "/goods/detail";
	}

	/**
	 * 商品详情页
	 * @param code
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/detail/{code}", method=RequestMethod.GET)
	@SuppressWarnings("unchecked")
	public String detailByCode(@PathVariable String code, Model model){
		String result = goodsHessian.getGoodsDetail(null, code, getMemberId());
		model.addAllAttributes(jsonToObj(result, Map.class));
		return "/goods/detail";
	}

	/**
	 * 商品评论
	 * @param goodsId
	 * @param grade
	 * @param pageNumber
	 * @param pageSize
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/goods/comments")
	@ResponseBody
	public String getGoodsComments(Long goodsId, Integer grade, Integer pageNumber, Integer pageSize, HttpServletResponse response) {
		return commentHessian.getGoodsCommentPageData(null, goodsId, grade, pageNumber, pageSize);
	}
	
	/**
	 * 商品购买记录
	 * @param goodsId
	 * @param pageNumber
	 * @param pageSize
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/goods/buyRecords")
	@ResponseBody
	public String getGoodsBuyRecords(Long goodsId, Integer pageNumber, HttpServletResponse response) {
		return goodsHessian.getGoodsBuyRecords(goodsId, pageNumber, 20);
	}
	
	/**
	 * 商品列表页
	 * @param pageNumber
	 * @param pageSize
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/list**", method=RequestMethod.GET)
	@SuppressWarnings("unchecked")
	public String list(Integer pageNumber, Integer pageSize, HttpServletRequest request, ModelMap model){
		String uri = StringUtils.substringBefore(request.getRequestURI(), ".jhtml");
		String result = goodsHessian.list(uri, null, getMemberId(), getCurrStoreId(), pageNumber, pageSize, "listPluginBundle");
		model.addAllAttributes(jsonToObj(result, Map.class));
		
		model.addAttribute("uri", StringEscapeUtils.escapeHtml4(uri));
		JSONArray selectorList = new JSONArray();
		/*selectorList.add(JSONObject.parseObject("{key: 'prescribeTypeList', name: '处方类型'}"));
		selectorList.add(JSONObject.parseObject("{key: 'medicalInsuranceTypeList', name: '医保类型'}"));
		selectorList.add(JSONObject.parseObject("{key: 'drugformList', name: '剂型'}"));*/
		model.addAttribute("selectorList", selectorList);
		return "/goods/list";
	}
	

	/**
	 * 获取浏览历史商品数据
	 * @return
	 */
	@RequestMapping(value = "/history", method = RequestMethod.POST)
	@ResponseBody
	public List<GoodsBean> history(HttpServletRequest request, HttpServletResponse response){
		String idStr = CookieUtils.get(request, HISTORY_GOODSIDS_COOKIE_NAME);
		if(StringUtils.isBlank(idStr)){
			return new ArrayList<GoodsBean>();
		}
		return jsonToList(memberExtendHessian.getHistoryGoods(idStr), GoodsBean.class);
	}

	@RequestMapping(value = "/searchDown", method = RequestMethod.GET)
	@ResponseBody
	public JSONArray searchTip(String q){
		JSONArray arr =  JSON.parseArray(goodsHessian.getSearchTip(q, 15));
		if(arr == null || arr.isEmpty()){
			return new JSONArray();
		}
		return arr;
	}


	/**
	 * 搜索
	 * @param keyword
	 * @param brandName 品牌名称
	 * @param categoryCode 分类code
	 * @param manufacturer 生产厂家
	 * @param drugForm	剂型
	 * @param prescribeType 处方类型
	 * @param medicalInsuranceType 医保
	 * @param goodsSort 排序
	 * @param pageNumber 页码
	 * @param model
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/search/{keyword}", method = RequestMethod.GET)
	public String search(@PathVariable String keyword,
			String brandName, String categoryCode, String manufacturer,
			String drugForm, String prescribeType,
			String medicalInsuranceType, String goodsSort, Integer pageNumber,
			HttpServletRequest request, Model model){

		Map<String, String> filterMap = new HashMap<String,String>();
		filterMap.put("brandName", brandName);
		filterMap.put("categoryCode", categoryCode);
		filterMap.put("manufacturer", manufacturer);
		filterMap.put("drugForm", drugForm);
		filterMap.put("prescribeType", prescribeType);
		filterMap.put("keyword", keyword);
		Long memberId = getMemberId();
		filterMap.put("memberId", memberId==null?"":String.valueOf(memberId));
		String json = goodsHessian.searchByKeyword(keyword,
				filterMap, goodsSort, pageNumber, 20);
		model.addAllAttributes(jsonToObj(json, Map.class));
		model.addAllAttributes(filterMap);
		String uri = StringUtils.substringBefore(request.getRequestURI(), ".jhtml");
		model.addAttribute("uri", StringEscapeUtils.escapeHtml4(uri));

		return  "/goods/search";
	}

	/**
	 * 品牌
	 * @return
	 */
	@RequestMapping(value = "/brand/list", method = RequestMethod.GET)
	public String brandList(Integer pageNumber, Model model){
		model.addAttribute("pager", jsonToObj(goodsExtendHessian.getBrandPagerData(pageNumber, 20), Pager.class));
		return  "/brand/list";
	}

	/**
	 * 品牌详情
	 * @param brandId
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/brand-{brandId}", method = RequestMethod.GET)
	public String brand(@PathVariable Long brandId, Integer pageNumber, Model model){
		model.addAttribute("info", JSONObject.parseObject(goodsExtendHessian.getBrandGoodsPager(brandId, pageNumber, 20)));
		return "/brand/detail";
	}

	@RequestMapping(value = "/getRecommandGoods", method = RequestMethod.GET)
	@ResponseBody
	public List<GoodsBean> getRecommandGoods(Long goodsCategoryId, String goodsCategoryCode, Long tagId){
		return jsonToList(goodsHessian.getGoodsListData(goodsCategoryId, goodsCategoryCode, null, tagId, 5, false, null, getCurrStoreId(), null), GoodsBean.class);
	}
}